local Widget = require "widgets/widget"
local Image = require "widgets/image" -- 引入image控件
-- local UIAnim = require "widgets/uianim"


local Screen = require "widgets/screen"
-- local AnimButton = require "widgets/animbutton"
-- local ImageButton = require "widgets/imagebutton"
-- local Menu = require "widgets/menu"
-- local Text = require "widgets/text"
-- local TEMPLATES = require "widgets/redux/templates"
-- local Video = require "widgets/video"



local AnimButton = require "widgets/animbutton_npc_card"

local npc_cards_widget = Class(Screen, function(self, owner,attach)
    Screen._ctor(self, "npc_cards_widget")
    self.owner = owner
    self.attach = attach
end)


function npc_cards_widget:Create_Cards(ret_card_name)
    self.the_cards = {}
    
    for i = 1, 4, 1 do
        self.the_cards[i] = self:AddChild(AnimButton("npc_card_base",{
            scale_num = 1.2,
            scale_num_focus = 1.4,
            index = i,
        }))
        -- self.the_cards[i]:SetRotation(1.5)
    end

    self.the_cards[1]:SetPosition(-450,0)
    self.the_cards[2]:SetPosition(-150,0)
    self.the_cards[3]:SetPosition(150,0)
    self.the_cards[4]:SetPosition(450,0)

    for i, theCard in ipairs(self.the_cards) do
        theCard:SetOnClick(function()
            -- print("card click",self.owner)
            theCard:ClearFocus()
            for k, v in pairs(self.the_cards) do
                v:Disable() -- -- -- --无法点击，也不会触发 mouseover 事件
                v:SetOnClick(nil)   ---- 防止autoclick 再次执行
                -- v:SetRotation(0)
            end
            local tempInst = CreateEntity()
            tempInst._num = 1
            tempInst._down_flag = true
            local delta = 0.3
            tempInst.__task = tempInst:DoPeriodicTask(0.05,function()       ---- 卡牌翻转的 代码
                if tempInst._down_flag == true then
                    tempInst._num = tempInst._num - delta
                else
                    tempInst._num = tempInst._num + delta
                end
                theCard:SetScale(tempInst._num,theCard.scale_num_focus)
                if tempInst._num <= 0 then
                    tempInst._down_flag = false
                    ---- layer cover
                    theCard.anim:GetAnimState():OverrideSymbol("front","npc_cards",ret_card_name or "npc_card_test")
                    ---- layer cover
                elseif tempInst._num >= theCard.scale_num_focus then
                    theCard:SetScale(theCard.scale_num_focus,theCard.scale_num_focus)
                    tempInst.__task:Cancel()
                    tempInst:Remove()
                end
            end)

            if self.owner then
                self.owner:DoTaskInTime(4,function()
                    self.owner:PushEvent("npc_cards_sys.kill")
                    self.owner.replica.npc_base_lib:PushEvent("npc_cards_sys.clicked")
                end)
            end

        end)
    end

    if TUNING.NPC_CONFIG.CARD_AUTO_SELECT then
        local s_inst = CreateEntity()
        s_inst:DoTaskInTime(2.5,function()
            local ret_num = math.random(4)
            if self.the_cards[ret_num].onclick then
                self.the_cards[ret_num].onclick()
            end
            s_inst:Remove()
        end)
    elseif Input:ControllerConnected()  then    ---- 用手柄的话
        self.the_cards[1]:SetFocus()
        -- local ret_num = math.random(4)        
        -- -- self.the_cards[ret_num]:SetFocus()
        -- self.the_cards[ret_num].focus_flag = true
    end

end


function npc_cards_widget:Scale_Task_Start()
    local function ScaleTheWidget(tarWidget)
        if tarWidget == nil then
            return
        end
        local scrnw, scrnh = TheSim:GetScreenSize()
        local scaleNum = scrnh/1080
        tarWidget:SetScale(scaleNum)
    end
    ScaleTheWidget(self)
    self.scale_inst = CreateEntity()
    self.scale_inst_task = self.scale_inst:DoPeriodicTask(1,function()
        ScaleTheWidget(self)
    end)
end

function npc_cards_widget:OnControl(control, down)  ------ 该API 会拦截原有的API，使鼠标点击不了（可能和 _base 有关，没深入验证），注意处理。
    if control == nil or down == nil then
        return
    end

    -- if down == true then
    --     print(control,down,"++++++++",math.random(5))
    -- end
    ------------- if npc_cards_widget._base.OnControl(self, control, down) then return true end  --- 这个没啥用

    if not down then                                ---- down is true
        if control == CONTROL_ACCEPT then
            ----- 注意需要配合  button  的 focus fn 进行 index 替换   _focus_index(计数用)    _focus_button（失去焦点用）
            local index_num = self._focus_index or 1
            if self.the_cards[index_num].onclick then
                self.the_cards[index_num].onclick()
            end
            return true
        -- elseif control == CONTROL_OPEN_DEBUG_CONSOLE then
        --     return true
        elseif control == CONTROL_CANCEL and TUNING.NPC_MOD_TEST_DEBUG == true  then
            self:Close()
        end
    end


    ----- 处理手柄摇杆 
    ------ 右摇杆（会自动定时跳,不用上inst.task了）： CONTROL_PREVVALUE （左）  CONTROL_NEXTVALUE （右）
    ------ 右摇杆（上下不会自动跳）  CONTROL_INVENTORY_UP    CONTROL_INVENTORY_DOWN
    if down == true and ( control == CONTROL_PREVVALUE or control == CONTROL_NEXTVALUE ) then
        local index_num = self._focus_index or 1
        if control == CONTROL_PREVVALUE then
            index_num = index_num  - 1
        elseif control == CONTROL_NEXTVALUE then
            index_num = index_num + 1
        end
        index_num = math.clamp(index_num,1,4)
        if self._focus_button then
            self._focus_button:OnLoseFocus()
        end
        self.the_cards[index_num]:OnGainFocus()        
    end

end

function npc_cards_widget:Close()
    if self.scale_inst_task then
        self.scale_inst_task:Cancel()
        self.scale_inst_task = nil
        self.scale_inst:Remove()
    end
    TheFrontEnd:PopScreen(self)  ----- 退出界面操作拦截
    self:Kill()
end

return npc_cards_widget